package com.yx.front.controller;

import com.yx.front.config.global.BizException;
import com.yx.front.config.global.CommonResult;
import com.yx.front.manager.OssFileUpManager;
import com.yx.front.utils.FileTypeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author YangXiong
 */
@Api(tags = "阿里云OSS文件上传、下载、删除API")
@RequestMapping("file")
@RestController
public class OssFileController {
    private static final String ERROR = "error";
    @Resource
    private OssFileUpManager oosFileUpManager;

    @Resource
    private FileTypeUtil fileTypeUtil;

    @ApiOperation(value = "文件上传")
    @PostMapping("upload")
    public CommonResult<String> upload(@RequestParam("file") MultipartFile file) throws UnsupportedEncodingException {
        if (file.isEmpty()) {
            return CommonResult.fail("文件为空");
        }
        //校验文件是否是我们允许的类型
        String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String res = fileTypeUtil.isOneType(type);
        if (ERROR.equals(res)) {
            throw new BizException(type + "格式文件暂时不支持上传");
        }
        String result = oosFileUpManager.upload(file);
        return CommonResult.success(result);
    }

    @ApiOperation(value = "文件下载")
    @GetMapping(value = "download")
    public CommonResult<CommonResult<String>> download(@RequestParam String fileName, HttpServletResponse response) throws Exception {
        return CommonResult.success(oosFileUpManager.download(fileName, response));

    }
}
